﻿#include <iostream>
#include <fstream>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>

#define SERVER_IP "127.0.0.1"
#define PORT 12345
#define CHUNK_SIZE 1024

void receiveFile(const char* outputFilename) {
    int sock;
    struct sockaddr_in serverAddr;
    char buffer[CHUNK_SIZE];

    // 创建套接字
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }

    // 配置服务器地址
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    inet_pton(AF_INET, SERVER_IP, &serverAddr.sin_addr);

    // 连接服务器
    if (connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        perror("connect");
        close(sock);
        exit(1);
    }

    std::cout << "已连接到服务器。" << std::endl;

    // 打开输出文件
    std::ofstream file(outputFilename, std::ios::binary);
    if (!file.is_open()) {
        perror("打开输出文件失败");
        close(sock);
        exit(1);
    }

    // 接收数据
    ssize_t bytesReceived;
    while ((bytesReceived = recv(sock, buffer, CHUNK_SIZE, 0)) > 0) {
        file.write(buffer, bytesReceived);
    }

    std::cout << "文件接收完成。" << std::endl;

    file.close();
    close(sock);
}

int main() {
    const char* outputFilename = "received_file_tcp.dat"; // 接收保存的文件名
    receiveFile(outputFilename);
    return 0;
}
